﻿using System;
using System.Web.Mvc;

namespace OrderingPlatform.MvcExtension
{
    public class ImageResult : ActionResult
    {
        private readonly string _format;
        private readonly string _noFilePath;
        public readonly byte[] Buffer;
        public ImageResult(byte[] buffer, string noFilePath = "/images/nopic.gif", string format = "png")
        {

            _format = format.ToLower();
            _noFilePath = noFilePath;
            Buffer = buffer;

        }

        public override void ExecuteResult(ControllerContext context)
        {
            context.HttpContext.Response.Clear();
            switch (_format)
            {
                case "bmp": context.HttpContext.Response.ContentType = "image/bmp";
                    break;
                case "gif": context.HttpContext.Response.ContentType = "image/gif";
                    break;
                case "jpeg": context.HttpContext.Response.ContentType = "image/jpeg";
                    break;
                case "png": context.HttpContext.Response.ContentType = "image/png";
                    break;
                case "tiff": context.HttpContext.Response.ContentType = "image/tiff";
                    break;
                case "jpg": context.HttpContext.Response.ContentType = "image/jpg";
                    break;
                default: context.HttpContext.Response.ContentType = "image/png";
                    break;
            }
            try
            {
                if (Buffer == null)
                {
                    context.HttpContext.Response.TransmitFile(_noFilePath);
                }
                else
                {
                    context.HttpContext.Response.Cache.SetNoStore();
                    context.HttpContext.Response.BinaryWrite(Buffer);
                }
            }
            catch (Exception ex)
            {
                context.HttpContext.Response.AddHeader("CRIC.ERROR", ex.Message);
                context.HttpContext.Response.AddHeader("Content-type", "image/jpg");
                context.HttpContext.Response.TransmitFile(_noFilePath);
            }
        }
    }
}
